﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LoveMusic.Models;
using System.Web.Security;
using System.Net;

namespace LoveMusic.Controllers
{
    public class Mp3Controller : BaseController, IDisposable
    {
        #region private

        private readonly IDataContext _dataContext;

        private IDataContext DataContext
        {
            [System.Diagnostics.DebuggerStepThrough]
            get
            {
                return _dataContext;
            }
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SongController"/> class.
        /// </summary>
        /// <param name="dataContext">The data context.</param>
        /// <param name="userManager">The membership provider that will be used.</param>
        public Mp3Controller(IDataContext dataContext, MembershipProvider userManager)
            : base(userManager)
        {
            _dataContext = dataContext;
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SongController"/> class.
        /// </summary>
        public Mp3Controller()
            : this(new ModelDataContext(), Membership.Provider)
        {
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        [NonAction]
        public void Dispose()
        {
            if (_dataContext != null)
            {
                _dataContext.Dispose();
            }
        }

        #endregion

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult GetSongs(int storyId, int artistId)
        {
            List<SongSmallBin> songs = DataContext.GetSongs(storyId, artistId);
            //songs = ValidateUrl(songs);
            return Json(songs);
        }

        private List<SongSmallBin> ValidateUrl(List<SongSmallBin> songs)
        {
            List<SongSmallBin> resultSongs = new List<SongSmallBin>();
            foreach (var song in songs)
            {
                if (RemoteFileExists(song.mp3))
                {
                    resultSongs.Add(song);
                }
            }
            return resultSongs;
        }

        public class MyClient : WebClient
        {
            private bool headOnly;
            public bool HeadOnly
            {
                get { return headOnly; }
                set { headOnly = value; }
            }

            protected override WebRequest GetWebRequest(Uri address)
            {
                WebRequest req = base.GetWebRequest(address);
                if (HeadOnly && req.Method == "GET")
                {
                    req.Method = "HEAD";
                }
                return req;
            }
        }

        ///
        /// Checks the file exists or not.
        ///
        /// The URL of the remote file.
        /// True : If the file exits, False if file not exists
        private bool RemoteFileExists(string url)
        {
            try
            {
                using (MyClient client = new MyClient())
                {
                    client.HeadOnly = true;
                    byte[] body = client.DownloadData(url); // note should be 0-length
                    string contentType = client.ResponseHeaders["content-type"];
                    client.HeadOnly = false;
                    // check 'tis not binary... we'll use text/, but could
                    // check for text/html
                    if (
                   "audio/mpeg" == contentType ||
                   "audio/mpeg3" == contentType ||
                   "audio/x-mpeg-3" == contentType ||
                   "video/mpeg" == contentType ||
                   "video/x-mpeg" == contentType ||
                   "APPLICATION/OCTET-STREAM" == contentType
                   )
                    {
                        return true;
                    }
                    else
                        return false;
                }

                ////Creating the HttpWebRequest
                //HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                ////Setting the Request method HEAD, you can also use GET too.
                //request.Method = "HEAD";
                ////Getting the Web Response.
                //HttpWebResponse response = request.GetResponse() as HttpWebResponse;
                ////Returns TURE if the Status code == 200
                //return (response.StatusCode == HttpStatusCode.OK);
            }
            catch
            {
                //Any exception will returns false.
                return false;
            }
        }
    }
}
